package com.tiancheng.trade.authserver.controller;

import com.tiancheng.trade.authserver.dto.*;
import com.tiancheng.trade.authserver.service.IAuthOauth2Service;
import com.tiancheng.trade.authserver.vo.ApplicationAccessTokenRequestVO;
import com.tiancheng.trade.authserver.vo.UserLogInResultVO;
import com.tiancheng.trade.authserver.vo.UserLoginInVO;
import com.tiancheng.trade.commom.core.data.Result;
import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

/**
 * oauth2相关接口controller
 */
@RestController
@RequestMapping("/auth/oauth2")
public class AuthOauth2Controller {
    @Resource
    private IAuthOauth2Service service;
    @Resource
    private HttpServletResponse response;

    private void setCookies(List<CookieDTO> cookies) {
        if (cookies != null) {
            cookies.forEach(cookieT -> {
                Cookie cookie = new Cookie(cookieT.getName(), cookieT.getValue());
                cookie.setDomain(cookieT.getDomain());
                cookie.setMaxAge(cookieT.getMaxAge());
                cookie.setPath(cookieT.getPath());
                cookie.setHttpOnly(cookieT.isHttpOnly());
                this.response.addCookie(cookie);
            });
        }
    }

    /**
     * oauth2授权,授权成功后返回code,前后端分离模式,由前端提交用户名密码,后端返回code给前端, 前端自行处理重定向
     *
     * @param applicationInfo 应用程序信息
     * @param userInfo        用户登陆信息
     */
    @PostMapping("/authorization")
    public Result<String> oauth2Authorization(Oauth2AuthorizationRequestDTO applicationInfo,
                                              @RequestBody UserLoginInVO userInfo) {
        Oauth2AuthorizationResult result = this.service.oauth2Authorization(applicationInfo, userInfo,
                true);
        //this.setCookies(result.getCookies());
        return Result.success(result.getOauth2Code());
    }

    @GetMapping("/callback")
    public Result<UserLogInResultVO> oAuthCallback(@RequestParam String code){
        return Result.success(this.service.oauth2UserInfoByCode(code));
    }

    /**
     * oauth2 access_token 换取接口, 第三方应用程序使用code来换取access_token, access_token的作用是换取用户信息
     */
    @PostMapping("/accessToken")
    public AccessTokenResponseDTO accessToken(AccessTokenRequestDTO param) {
        return this.service.getOauthAccessToken(param);
    }

    /**
     * 第三方应用程序通过在请求头中传递authorization(access_token)来获取用户信息
     */
    @GetMapping("/userInfo")
    public Result<UserLogInResultVO> oauth2UserInfo(@RequestHeader String authorization) {
        return Result.success(this.service.oauth2UserInfo(authorization));
    }

}
